// pages/comfirm-order/comfirm-order.js
import {
  getDeliveryFee,
  setProPay,
  wXappUpdateOrder,
  projPayUpdateOrder
} from '../../api/apis.js'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    buys: [],
    addressDetail: {},
    deliveryFee: 0,
    remark: '',
    name: '',
    phone: ''
  },
  /**
   * 生命周期函数--监听页面显示
   */
  // onShow: function () {
  //   this._getAddress()
  //   this._getConfirmProduct()
  // },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._getAddress()
    this._getConfirmProduct()
  },
  _getAddress() {
    let address = wx.getStorageSync("address")
    if (address) {
      this.setData({
        addressDetail: address
      })
    }
  },
  _getConfirmProduct() {
    let buys = wx.getStorageSync("confirmProduct")
    let ids = []
    buys.forEach((item) => {
      ids.push(item.product_Id)
    })
    this.setData({
      buys: buys,
      products: JSON.stringify(ids)
    })
    this._getTotal()
  },
  _getTotal() {
    let productTotal = 0
    this.data.buys.forEach((item) => {
      productTotal += item.count * item.price
    })
    this.setData({
      productTotal: productTotal.toFixed(2),
      total: (Number(productTotal) + Number(this.data.deliveryFee)).toFixed(2)
    })
  },
  setRemark(e) {
    this.setData({
      remark: e.detail.value
    })
  },
  nameInput(e) {
    this.setData({
      name: e.detail.value
    })
  },
  phoneInput(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  setOrder() {
    if (!this.data.name.trim()||!this.data.phone.trim()) {
      wx.showToast({
        title: '请填写完整购买信息',
        icon: 'none'
      })
      return false
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    let prodPay = []
    this.data.buys.forEach((item) => {
      prodPay.push({
        pid: item.product_Id,
        skuid: item.sku_id,
        num: item.count,
      })
    })
    setProPay({
      data: {
        openid: app.globalData.openid,
        name: this.data.name,
        phone: this.data.phone,
        prodPay: prodPay,
        remark: this.data.remark
      },
      success: res => {
        wx.hideLoading()
        if (res.state) {
          let params = JSON.parse(res.data.parameters)
          if (parseFloat(this.data.total) > 0) {
            wx.requestPayment({
              nonceStr: params.nonceStr,
              package: params.package,
              paySign: params.paySign,
              signType: params.signType,
              timeStamp: params.timeStamp,
              success: response => {
                wx.showToast({
                  title: '支付成功',
                  mask: true,
                  duration: 2000,
                  success: (e) => {
                    setTimeout(() => {
                      wx.navigateTo({
                        url: '../order-list/order-list',
                      })
                    }, 2000)
                  }
                })
              },
              complete: response => {
                if (response.errMsg == "requestPayment:cancel" || response.errMsg == "requestPayment:fail cancel") {
                  this._updateOrder(res, 'fail')
                }
              }
            })
          } else {
            this._updateOrder(res, 'ok')
          }
        }
      }
    })
  },
  _updateOrder(res, state) {
    projPayUpdateOrder({
      data: {
        orderid: res.data.out_trade_no,
        payStatus: state,
        payReamrk: '',
        openid: app.globalData.openid
      },
      success: res => {
        if (res.state) {
          wx.showToast({
            title: state == 'ok' ? '支付成功' : '支付失败',
            icon: 'none',
            mask: true,
            duration: 2000,
            success: (e) => {
              setTimeout(() => {
                wx.navigateTo({
                  url: '../order-list/order-list',
                })
              }, 2000)
            }
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})